<template>
  <div class="sched-table">
    <div class="table-download">
      <div>
        <a-button type="text" @click="addColumn">
          <template #icon>
            <FilterOutlined />
          </template>
          自定义列</a-button>
      </div>
      <a-button class="border-btn" @click="exportData">
        <template #icon>
          <UploadOutlined />
        </template>
        导出</a-button>
    </div>
    <a-table  v-if="tableData.columns.length > 0 || tableData.data.length > 0" :columns="tableData.columns" :data-source="tableData.data"
              :row-selection="{selectedRowKeys: tableData.selectedRowKeys, onChange: onSelectChange}"
              :scroll="{ x: 500}"
              :pagination="pagination"
              @change="handleTableChange"
              @resizeColumn="handleResizeColumn"
              :row-key="(record) => record.id"
              :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)"
    >
      <template #bodyCell="{ column, text }">
        <template v-if="column.key === 'a7'">
        <span> <span :class="{
          'type-circle': true,
        'type-circle-1': text === '在航',
        'type-circle-2': text === '装货',
        'type-circle-3': text === '卸货',
        'type-circle-4': text === '空载'
        }">·</span>{{text}}</span>
        </template>
        <template v-if="column.key === 'a10'">
          <span :style="text === '是'? {color: '#FA6400'} : {color: '#6B7A8B'}"> {{text}}</span>
        </template>
        <template v-if="column.key === 'tradeBody'">
                  <span v-for="item in tradeareas" :key="item.label">
                        <span v-if="item.value === text">{{item.label}}</span>
                    </span>
        </template>
        <template v-if="column.key === 'tradeType'">
         <span v-for="item in areas" :key="item.label">
            <span v-if="item.value === text">{{item.label}}</span>
          </span>
        </template>
      </template>
    </a-table>
    <a-skeleton v-else active />
    <CustomColumnModel ref="columnForm"
                       @saveColumn="onSaveColumn"
                       :customData="customData"
                       :columSaveData="columSaveData"
                       :module="activeModule"
    />
  </div>
</template>
<script setup>
import {ref, getCurrentInstance, reactive, onMounted, watch, defineProps, defineEmits} from 'vue';
import CustomColumnModel from './CustomColumnModel.vue'
const { proxy  } = getCurrentInstance()
import {UploadOutlined, FilterOutlined} from '@ant-design/icons-vue';
const customData = ref([])
const activeModule = ref('sp_arrange_scheme_detail')
const columSaveData = ref([])
const columnForm = ref()
const customUpdate = ref('')
const emit = defineEmits(['exportData'])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
  {
    label: '国贸&新贸',
    value: 3
  },
])
// 贸易类型
const areas = ref([
  {
    label: '长协',
    value: 1
  },
  {
    label: '中期',
    value: 2
  },
  {
    label: '现货',
    value: 3
  }
])
const pagination = ref({
  pageSize: 10,
  current: 1,
  total: 0,
  showQuickJumper: true,
  showSizeChanger: true,
  showTotal: total => `共 ${total} 条`,
  size: 'small'
})
const tableData = reactive({
  columns: [],
  data: [],
  customData:  customData.value,
  selectedRowKeys: [],
  selectedRowsArr: {}
})
const props = defineProps({
  isRedraw: {
    type: Number,
    default: 0
  },
  conId: {
    type: String,
    default: ''
  }
})
const newConId = ref('')
watch(() => props.conId, (newVal) => {
  newConId.value = newVal
  getPageList()
  getUserColum()
})
watch(() => props.isRedraw, (newVal) => {
  console.log('我的图表需要重绘不', newVal)
  getPageList()
  getUserColum()
})
const onSelectChange = (selectedRowKeys, selectedRows) => {
  console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  tableData.selectedRowKeys = selectedRowKeys
  tableData.selectedRowsArr = selectedRows
  emit('exportData', selectedRows)
};
const addColumn = () => {
  customUpdate.value = ''
  let list = []
  let newList = []
  list = tableData.columns
  newList = JSON.parse(JSON.stringify(list))
  console.log('保存的列',newList)
  if (newList.length > 0) {
    newList.map(item => {
      if (item.key !== 'tags') {
        columSaveData.value.push(item.key)
      }
    })
  }
  columnForm.value.showModal()
  console.log('获取到保存的值没', columSaveData)
}
const onSaveColumn = (item) => {
  console.log('传回来的item', item)
  customUpdate.value = item
  columSaveData.value = []
  getPageList()
  getUserColum()
}
/**
 * 获取显示列
 * */
const getPageList = () => {
  let customObj = {
    module: activeModule.value
  }
  /**
   * 列表展示所有列
   * */
  proxy.$api.getTableColumnCustom(customObj).then(res => {
    console.log('成功了没列', res)
    customData.value = res.resultObject
  })
}
/**
 * 获取表格数据
 * */
const getUserColumPage = () => {
  let newObj = {
    pageNum: pagination.value.current,
    pageSize: pagination.value.pageSize,
    resourceContract: newConId.value
  }
  /**
   * 表格数据
   * */
  proxy.$api.postGanttTable(newObj).then(res => {
    console.log('表格数据', res, proxy)
    tableData.data = res.resultObject.list
    if (tableData.data &&  tableData.data.length > 0) {
      tableData.data.map(item => {
        Object.assign(item, {
          id: item.id.toString()
        })
      })
    }
    pagination.value.total = res.resultObject.total
  })
}
/**
 * 表格字段
 * */
const getUserColum = () => {
  /**
   * 用户自定义列
   * */
  proxy.$api.getTableColumn({module: 'sp_year_plan_scheme_detail'}).then(res => {
    console.log('成功了没', res)
    let resData = res.resultObject
    let newData = []
    // let firstObj =  {
    //   title: '序号',
    //   dataIndex: 'orderNum',
    //   key: 'orderNum',
    //   width: '80px',
    //   fixed: 'left',
    //   align: 'center'
    // }
    let lastObj =  {
      title: '操作',
      key: 'tags',
      fixed: 'right',
      align: 'left',
      resizable: true,
      width:150
    }
    if ( customData.value.length > 0) {
      resData.map((item) => {
        customData.value.map(cItem => {
          if (item.columnKey === cItem.key) {
            let obj =  {
              title: '',
              dataIndex: '',
              key: '',
              ellipsis: true,
              resizable: true,
              align: 'left',
              width: 150
            }
            Object.assign(obj, {
              title: cItem.name,
              dataIndex: item.columnKey,
              key: item.columnKey,
              fixed: item.fixed ===1 ? 'left' : '',
            })
            newData.push(obj)
          }
        })
      })
      // tableData.columns.push(lastObj)
      tableData.columns = [...newData]
      const hash = {}
      tableData.columns = tableData.columns.reduce((item,next) => {
        hash[next.dataIndex]? '' : hash[next.dataIndex] = true && item.push(next)
        return item
      }, [])
    }
    getUserColumPage()
  })
}
const handleTableChange = (paginationpage) => {
  pagination.value.pageSize = paginationpage.pageSize
  pagination.value.current = paginationpage.current
  pagination.value.total = paginationpage.total
  console.log('分页了', paginationpage)
  getUserColumPage()
}
/**
 * 导出
 * */
const exportList = ref({
  ids: [],
  searchItem: ''
})
const exportData = (val) => {
  console.log('导出的数据', val)
  if (tableData.selectedRowsArr && tableData.selectedRowsArr.length > 0) {
    tableData.selectedRowsArr.map(item => {
      exportList.value.ids.push(item.id)
    })
  }
  proxy.$api.postPageLngAddExport(exportList.value).then(res => {
    if (res.resultCode === 0) {
      message.success('导出成功')
      // 创建一个隐藏的链接元素用于下载
      let a = document.createElement('a');
      a.href = res.resultObject;
      // 模拟点击下载链接
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      // 清理下载链接元素
      document.body.removeChild(a);
    }
  })
}
import { useRouter } from "vue-router";
import {message} from "ant-design-vue";
const router = useRouter()
const goDtails = (id) => {
  router.push({
    path: '/plan/schedulingDetail',
    query: {
      id: id.toString()
    }
  })
}
const handleResizeColumn = (w, col) => {
  col.width = w
}
onMounted(() => {
  getPageList()
  getUserColum()
})
</script>

<style lang="scss" scoped>
.sched-table {
  width: 100%;
  padding: 32px 16px 16px 16px;
  background: #ffffff;
  border-radius: 4px;
  .table-download {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
  }
}
.table-btn-box {
  display: flex;
  text-align: center;
  .btn-1 {
    color: #0062AD;
    padding-left: 10px;
  }
  .btn-2 {
    color: #6B7A8B;
    border-right: 1px solid #DCDEE0;
    border-left: 1px solid #DCDEE0;
    padding-left: 10px;
  }
  .btn-3 {
    color: #F5001D;
    padding-left: 10px;
  }
}
.type-circle {
  font-weight: 800;
  padding-right: 5px;
  &-1 {
    color: #27AF91;
  }
  &-2 {
    color: #0062AD;
  }
  &-3 {
    color: #FA6400;
  }
  &-4 {
    color: #F7B500;
  }
}
</style>
